<template>
    <div class="cardArea">
        <!-- 密码头像区域 -->
        <div class="personalArea">
            <div class="personalArea_avatar">
                <a-avatar
                v-if="currentUser.avatar"
                size="default"
                :src="currentUser.avatar"
                class="defaultAvatar"
            />
            <img v-else src="@/assets/images/defaultAva.png" alt="" class="defaultAvatar" />
                <span class="personalArea_avatar_txt">{{ currentUser.name }}</span>
            </div>
        </div>
        <div class="formArea">


            <a-form
                ref="formRef"
                name="custom-validation"
                :model="formState"
                :rules="rules"
                v-bind="layout"

                @finish="handleFinish"
                @finishFailed="handleFinishFailed"
            >
                <a-form-item has-feedback label="原密码" name="oldpass">
                  <a-input v-model:value="formState.oldpass" type="password" autocomplete="off" />
                </a-form-item>
                <a-form-item has-feedback label="新密码" name="pass">
                <a-input v-model:value="formState.pass" type="password" autocomplete="off" />
                </a-form-item>
                <a-form-item has-feedback label="确认密码" name="checkPass">
                <a-input v-model:value="formState.checkPass" type="password" autocomplete="off" />
                </a-form-item>
                <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
                <a-button class="btn" type="primary" html-type="submit" @click="onSubmit">修改</a-button>
                </a-form-item>
            </a-form>
        </div>
    </div>
</template>


<script lang="ts">
import { defineComponent, ref, reactive} from 'vue'
import { Storage } from '@/utils/Storage';
import {updatePassword} from '@/api/account/account'
import type { Rule } from 'ant-design-vue/es/form';
import { message ,type FormInstance} from 'ant-design-vue';
import { LOGIN_NAME } from '@/router/constant';
import { useRouter} from 'vue-router';
import { nextTick} from 'vue';
import { useKeepAliveStore } from '@/store/modules/keepAlive';
import { useUserStore } from '@/store/modules/user';



interface FormState {
  oldpass: string;
  pass: string;
  checkPass: string;
}

export default defineComponent({

    setup() {
        const router = useRouter();
        const userStore = useUserStore();
        const keepAliveStore = useKeepAliveStore();
        const formRef = ref<FormInstance>();
        const formState = reactive<FormState>({
            oldpass: '',
            pass: '',
            checkPass: ''
        });
        let currentUser = Storage.Get('power-user') // 用户信息

        let validatePass = async (_rule: Rule, value: string) => {
            if (value === '') {
                return Promise.reject('请输入新密码');
            } else {
                if (formState.checkPass !== '') {
                    if(formRef.value) formRef.value.validateFields('checkPass');
                }
                return Promise.resolve();
            }
        };
        let validatePass2 = async (_rule: Rule, value: string) => {
            if (value === '') {
                return Promise.reject('请再次输入新密码');
            } else if (value !== formState.pass) {
                return Promise.reject("两次输入的密码不同!");
            } else {
                return Promise.resolve();
            }
        };
        let validatePass3 = async (_rule: Rule, value: string) => {
          if (value === '') {
            return Promise.reject('请输入原密码');
          } else {
            // if (formState.oldpass !== '') {
            //   if(formRef.value) formRef.value.validateFields('oldpass');
            // }
            return Promise.resolve();
          }
        };
        const rules: Record<string, Rule[]> = {
          oldpass: [{ required: true, validator: validatePass3, trigger: 'change' }],
          pass: [{ required: true, validator: validatePass, trigger: 'change' }],
          checkPass: [{ validator: validatePass2, trigger: 'change' }],
        };
        const layout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 14 },
        };
        const handleFinish = (values: FormState) => {
            console.log(values);
        };
        const handleFinishFailed = errors => {
            console.log(errors);
        };
        const resetForm = () => {
            if(formRef.value) formRef.value.resetFields();
        };
        // const handleValidate = (...args) => {
        //     console.log(args);
        // };

        function checkPassWord(newpass) {
            if(newpass.indexOf(" ") != -1){
                //提示
                //this.$message.warning("密码不能含有空格");
                return 0;
            }
            if(newpass.length < 8){
                //提示
                //this.$message.warning('请输入8 ~ 16位的字母、数字、特殊字符')
                return 0;
            }
            var checkNum = 0;
            //是否包含小写字母
            if(newpass.match(/([a-z])+/)){
                checkNum++;
            }
            //是否包含数字
            if(newpass.match(/([0-9])+/)){
                checkNum++;
            }
            //是否包含大写字母
            if(newpass.match(/([A-Z])+/)){
                checkNum++;
            }
            //是否包含特殊字符
            if(newpass.match(/[^a-zA-Z0-9]+/)){
                checkNum++;
            }
            return checkNum;
        }

        // 提交表单
        function onSubmit() {
          if(formState.oldpass == '' || formState.pass == '' || formState.checkPass == ''){
            message.error('请输入密码！')
            return false
          }
          if(formState.oldpass == formState.pass){
            message.error('新密码不能与原密码相同')
            return false
          }
          if(checkPassWord(formState.oldpass) < 3){
            message.error('原密码格式错误，请输入8 ~ 16位的字母、数字、特殊字符')
            return false
          }else if (checkPassWord(formState.checkPass) < 3 || checkPassWord(formState.pass) < 3 ) {
                message.error('请输入8 ~ 16位的字母、数字、特殊字符')
                return false
            }else{
                updatePassword({
                    userid: currentUser.userid,
                    password: formState.oldpass,
                    newPassword: formState.pass,
                }).then(res =>{
                    console.log(res)
                    message.info('修改成功请重新登录')
                    doLogout();
                })
            }
        };
        // 退出登录
        const doLogout = async () => {
            // todo 退出登录
            await userStore.logout();

            keepAliveStore.clear();
            // 移除标签页
            localStorage.clear();
            await nextTick();
            router.replace({
            name: LOGIN_NAME,
            query: {
                redirect: '/home',
            },
            });
        };

        const onClose = (e: MouseEvent) => {
            console.log(e, 'I was closed.');
        };

        return {
            currentUser,
            onSubmit,
            onClose,
            formState,
            formRef,
            rules,
            layout,
            handleFinishFailed,
            handleFinish,
            resetForm,
            // handleValidate,
        }
    },
})
</script>

<style lang="less" scoped>
/deep/ .ant-form-item label {
  color: #adadae;
}
.cardArea {
  background-color: #fff;
  min-height: 700px;
}

.personalArea {
  padding: 55px;
  margin-right: 5%;
}

.personalArea_avatar {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.personalArea_avatar_img {
  border-radius: 50%;
  width: 80px;
  object-fit: cover;
  border: 1px solid #f5f5f5;
}

.personalArea_avatar_txt {
  margin-top: 10px;
  font-weight: 550;
  font-size: 18px;
}

.defaultAvatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

.formArea{
    width: 600px;
    height: 300px;
    margin: auto;
}
.btn{
  margin-left: 40%;
}
</style>
